package com.org.cys.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.org.cys.controller.base.BaseController;
import com.org.cys.pojo.base.Page;
import com.org.cys.service.system.PrivilegeRoleService;
import com.org.cys.service.system.PrivilegeService;
import com.org.cys.service.system.RoleService;
import com.org.cys.service.system.UserRoleService;
import com.org.cys.util.ExportExcel;
import com.org.cys.util.MapUtil;
import com.org.cys.util.PageData;
import com.org.cys.util.StringUtil;  
  
/**
 * 角色Controller
 * @author caiyushen
 * */  
@Controller  
@RequestMapping("/role")  
public class RoleController extends BaseController{  
    
	private static Logger logger = Logger.getLogger(RoleController.class);
	
	@Resource(name="roleServiceImpl")
    private RoleService roleService;  
	
	@Resource(name="privilegeServiceImpl")
	private PrivilegeService privilegeService;
	
	@Resource(name="privilegeRoleServiceImpl")
	private PrivilegeRoleService privilegeRoleService;
	
	@Resource(name="userRoleServiceImpl")
	private UserRoleService userRoleService;
   
   /**
     * 去用户列表页面
     * @author caiyushen
     * */
    @RequestMapping(value="/toList",method = RequestMethod.GET)  
    public String toList() throws Exception{  
        return "role/list";  
    }  
	
	
    /**
     * 获取列表信息
     * @param page 分页实体类
     * @author caiyushen
     * */
    @ResponseBody
    @RequestMapping(value="/list",method = RequestMethod.GET)
    public PageData list(Page page){
    	PageData pd = new PageData();
    	try{
    		pd = this.getPageData();
    		page.setPd(pd);
    		logger.info("method list() param: " + page.toString());
    		List<PageData> dataList = roleService.dataList(page);
    		pd.put("dataList", dataList);
    		pd.put("total",page.getTotalResult());
    	}catch(Exception e){
    		logger.error(e.toString(),e);
    	}
    	return pd;
    }
    
    /**
     * 新增Role
     * @author caiyushen
     * */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public PageData add(@RequestBody PageData pd){
    	logger.info("method add() param: "+pd.toString());
    	PageData result = new PageData();
    	try{
    		roleService.save(pd);
    		result.put("success", true);
    	}catch(Exception e){
    		logger.error(e.toString(),e);
    		result.put("success", false);
    	}
    	return result;
    }
   
    
    /**
     * 修改Role
     * @author caiyushen
     * */
    @ResponseBody
    @RequestMapping(method = RequestMethod.PUT)
    public PageData update(@RequestBody PageData pd){
    	logger.info("method update() param: "+pd.toString());
    	PageData result = new PageData();
    	try{
    		roleService.update(pd);
    		result.put("success", true);
    	}catch(Exception e){
    		logger.error(e.toString(),e);
    		result.put("success", false);
    	}
    	return result;
    }
    
    /**
     * 删除Role
     * @author caiyushen
     * */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE)
    public PageData delete(@RequestBody PageData pd){
    	logger.info("method delete() param: "+pd.toString());
    	PageData result = new PageData();
    	try{
    		//判断该角色是否存在用户关联
        	List<PageData> midList = userRoleService.getListByRoleId(MapUtil.getLong(pd,"id"));
        	if(midList.size()>0){
        		result.put("success", false);
        		result.put("error", "请先删除该角色下的用户关联！");
        	}else{
        		roleService.delete(pd);
        		result.put("success", true);
        	}
    	}catch(Exception e){
    		logger.error(e.toString(),e);
    		result.put("success", false);
    	}
    	return result;
    }
    
    /**
     * 导出Excel数据
     * */
    @RequestMapping(value="/exportExcel",method = RequestMethod.GET)
    public ModelAndView exportExcel(){
    	ModelAndView mv = new ModelAndView();
    	PageData pd = new PageData();
    	pd = this.getPageData();
    	try{
    		Map<String,Object> dataMap = new HashMap<String,Object>();
			List<String> titles = new ArrayList<String>();
		    titles.add("角色名称"); //1	
		    titles.add("备注"); //2	
			dataMap.put("titles", titles);
			List<PageData> varOList = roleService.listAll(pd);
			List<PageData> varList = new ArrayList<PageData>();
			for(int i=0;i<varOList.size();i++){
				PageData vpd = new PageData();
				vpd.put("var1", varOList.get(i).getString("roleName"));//1
				vpd.put("var3", varOList.get(i).getString("roleRemark"));//2
				varList.add(vpd);
			}
			dataMap.put("varList", varList);
			ExportExcel erv = new ExportExcel();
			mv = new ModelAndView(erv,dataMap);
    	}catch(Exception e){
			logger.error(e.toString(), e);
		}
    	
    	return mv;
    }
    
    
    /**
     * 获取权限树
     * */
    @ResponseBody
    @RequestMapping(value="/getPrivilegeTree",method = RequestMethod.GET)
    public PageData getPrivilegeTree(){
    	logger.info("method getPrivilegeTree()");
    	PageData result = new PageData();
    	try {
    		//获取所有一级权限树
			List<PageData> parentList = privilegeService.getParentList(new PageData());
			if(StringUtil.checkObj(parentList)){
				int parentListSize = parentList.size();
				List<PageData> treeList = new ArrayList<>();
				for(int i=0;i<parentListSize;i++){
					PageData parent = parentList.get(i);
					parent.put("text", MapUtil.getString(parent, "privilegeName"));
					List<PageData> childrenList = privilegeService.getListByParentId(MapUtil.getLong(parent,"id"));
					int childrenListSize = childrenList.size();
					for(int j=0;j<childrenListSize;j++){
						PageData children = childrenList.get(j);
						children.put("text", MapUtil.getString(children, "privilegeName"));
					}
					parent.put("children", childrenList);
					treeList.add(parent);
				}
				result.put("treeList", treeList);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
    	logger.info("method getPrivilegeTree() result: "+ result.toString());
    	return result;
    }
    
    /**
     * 权限分配
     * @param pd roleId 角色id
     * @param pd privilegeStr 权限id组（使用英文逗号隔开）
     * */
    @ResponseBody
    @RequestMapping(value="/savePrivilegeRole",method = RequestMethod.POST)
    public PageData savePrivilegeRole(@RequestBody PageData pd){
    	logger.info("method savePrivilegeRole() param pd:"+pd.toString());
    	PageData result = new PageData();
    	List<PageData> dataList = new ArrayList<>();
    	//获取用户主键id
    	Long roleId = MapUtil.getLong(pd, "roleId");
    	//获取权限id组
    	String privilegeStr = MapUtil.getString(pd, "privilegeStr");
    	//分割权限id
    	String[] privilegeArray = privilegeStr.split(",");
    	//封装进入dataList
    	for(int i=0;i<privilegeArray.length;i++){
    		PageData privilegeRole = new PageData();
    		privilegeRole.put("privilegeId", privilegeArray[i]);
    		privilegeRole.put("roleId",roleId);
    		dataList.add(privilegeRole);
    	}
    	if(StringUtil.checkObj(roleId)){
    		try {
    			privilegeRoleService.saveBatchByRoleId(dataList,roleId);
    			result.put("success", true);
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			result.put("success", false);
    		}
    	}
    	return result;
    }
    
    /**
     * 根据角色id获取权限数据
     * */
    @ResponseBody
    @RequestMapping(value="/getPrivilegeByRoleId",method = RequestMethod.GET)
    public PageData getPrivilegeByRoleId(@RequestParam Long roleId){
    	logger.info("method getPrivilegeByRoleId() param: roleId:"+roleId);
    	PageData result = new PageData();
    	List<PageData> dataList = new ArrayList<>();
    	try {
			dataList = privilegeRoleService.getListByRoleId(roleId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	result.put("dataList", dataList);
    	return result;
    }
    
    
    
}  